//
//  YXUserInfoManager.m
//  CaoShi
//
//  Created by 杨旭 on 2018/10/9.
//  Copyright © 2018年 杨旭. All rights reserved.
//

#import "YXUserInfoManager.h"
#import "YXLoginViewController.h"
#define KEY @"USERINFO"

static YXUserInfoModel *userInfoModel = nil;
@implementation YXUserInfoManager

+ (YXUserInfoManager *)shareUserInfoManager {
    static YXUserInfoManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[YXUserInfoManager alloc] init];
    });
    return manager;
}

/** 保存用户信息 */
+ (void)saveUserInfoWithModel:(YXUserInfoModel *)entity {
    //NSUserDefaults 继承于NSObject, 单例模式设计, 存储信息采用键值对的形式
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:entity];
    //存数据
    [userDefault setObject:data forKey:KEY];
    //NSUserDefaults, 不是立即写入,写完之后需要同步一下
    [userDefault synchronize];
    
}
/** 清空用户信息 */
+ (void)cleanUserInfo {
    
    //创建对象
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    //移除数据
    [userDefault removeObjectForKey:KEY];
    //同步
    [userDefault synchronize];
    
    userInfoModel = nil;
    
}
/** 获取用户信息 */
+ (YXUserInfoModel *)getUserInfo {
    
    //判断之前是否去过,如果去过,直接返回,如果没有,从沙盒中读取
    if (!userInfoModel) {
        
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        //获取用户信息
        NSData *data = [userDefault objectForKey:KEY];
        //判断是否有值
        if (data) {
            
            userInfoModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        } else {
            
            userInfoModel = nil;
        }
        
    }
    
    return userInfoModel;
    
    
}
/** 判断用户登录状态 */
+ (BOOL)isLoad {
    
    if ([YXUserInfoManager  getUserInfo] == nil) {
        return NO;
    } else {
        return YES;
    }
    
}

/**  修改用户信息 */
+ (void)resetUserInfoMessageWithDic:(NSDictionary *)dic {
    
    YXUserInfoModel *model = [YXUserInfoManager getUserInfo];
    NSString *key = [dic allKeys].firstObject;
    if ([key isEqualToString:kHeaderPic]) {
        model.pic = dic[@"pic"];
        
    }

    if ([key isEqualToString:kUserAddress]) {
        model.address = dic[@"address"];
        
    }
    if ([key isEqualToString:kPHONE]) {
        model.phone = dic[@"phone"];
        
    }
    
    
    [YXUserInfoManager saveUserInfoWithModel:model];
    
    //    NSLog(@"%@------%@", model.workState, [self getUserInfo].workState);
    
}


+ (void)changeRootViewColToLoginVC{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    YXLoginViewController *vc = [[YXLoginViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
    nav.navigationController.navigationBar.hidden = YES;
    [window.rootViewController presentViewController:nav animated:YES completion:nil];
}



@end
